package com.api.weavernorth.action.sap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weavernorth.humanresource.SalarRangeUtil;
import com.weavernorth.util.JdeUtil;
import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import sun.misc.BASE64Encoder;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.Iterator;

@Path("/weavernorth/action/sap/Sap")
public class Sap extends HttpServlet {
    private static Log log = org.apache.commons.logging.LogFactory.getLog(Sap.class.getName());

    @GET
    @Path("/getData")
    @Produces(MediaType.TEXT_PLAIN)
    public String getDatas(@Context HttpServletRequest request, @Context HttpServletResponse response) {

        log.info("区域经理推送sap开始");
        //报文请求体
        StringBuffer requestXml;
        //数据库操作
        RecordSet rs = new RecordSet();
        RecordSet rsSelect = new RecordSet();
        RecordSet rsUpdate = new RecordSet();
        //推送
        SalarRangeUtil salarRangeUtil = new SalarRangeUtil();
        //查询区域经理建模表的sql
        String strQyjlSql = "select * from uf_qyjlpfhzb where (tsjg is null or tsjg=1)";
        log.info("查询区域经理建模表的sql:" + strQyjlSql);
        rs.executeQuery(strQyjlSql);

        requestXml = new StringBuffer();
        //拼接请求体
        requestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>" +
                "<soapenv:Header/>" + "<soapenv:Body>" + "<urn:ZHRI_075>" + " <RETURN>" +
                "<!--Zero or more repetitions:-->" +
                "<item>" +
                "<TYPE></TYPE>" +
                "<ID></ID>" +
                "<NUMBER></NUMBER>" +
                "<MESSAGE></MESSAGE>" +
                "<LOG_NO></LOG_NO>" +
                "<LOG_MSG_NO></LOG_MSG_NO>" +
                "<MESSAGE_V1></MESSAGE_V1>" +
                "<MESSAGE_V2></MESSAGE_V2>" +
                "<MESSAGE_V3></MESSAGE_V3>" +
                "<MESSAGE_V4></MESSAGE_V4>" +
                "<PARAMETER></PARAMETER>" +
                "<ROW></ROW>" +
                "<FIELD></FIELD>" +
                "<SYSTEM></SYSTEM>" +
                "</item>" +
                "</RETURN>" +
                "<T_9133>" +
                "<!--Zero or more repetitions:-->");

        while (rs.next()) {

            //获取员工编号
            String strYgbh = Util.null2String(rs.getString("gh"));
            log.info("员工编号：" + strYgbh);




            //拼接XML
            requestXml.append(" <item>" + "<PERNR>" + strYgbh + "</PERNR>");

            //获取CRM评分
            String strCRM = Util.null2String(rs.getString("crmpf"));
            log.info("CRM评分：" + strCRM);
            //拼接XML
            requestXml.append("<ZCRMPF>" + strCRM + "</ZCRMPF>");

            //获取零售运营评分
            String strLsyy = Util.null2String(rs.getString("lsyypf"));
            log.info("零售运营评分：" + strLsyy);
            //拼接XML
            requestXml.append("<ZLSYYPF>" + strLsyy + "</ZLSYYPF>");

            //获取服务标准评分
            String strFwbz = Util.null2String(rs.getString("fwbzpf"));
            log.info("服务标准评分：" + strFwbz);
            //拼接XML
            requestXml.append("<ZFWBZPF>" + strFwbz + "</ZFWBZPF>");

            //获取陈列管理
            String strClgl = Util.null2String(rs.getString("clglpf"));
            log.info("陈列管理评分：" + strClgl);
            //拼接XML
            requestXml.append("<ZCLGLPF>" + strClgl + "</ZCLGLPF>");

            //总得分
            String strZdf = Util.null2String(rs.getString("zdf"));
            log.info("总得分：" + strZdf);
            //拼接XML
            requestXml.append("<ZDF>" + strZdf + "</ZDF>");

            //评分日期
            String strPfrq = Util.null2String(rs.getString("pfrq"));
            log.info("评分日期：" + strPfrq);


            //姓名
            String strXm=Util.null2String(rs.getString("xm"));
            String strGzfw=salarRangeUtil.getGzfwFromUser(strXm);

            String strLockMess = salarRangeUtil.judgeLock(strGzfw, strPfrq);
            log.info("工资核算范围返回信息:" + strLockMess);
            if (!"".equals(strLockMess)) {
                strLockMess="工号为:"+strYgbh+","+strLockMess+"薪资核算结束后，工资范围解除锁定，流程可以继续提交";

                return strLockMess;

            }
            //zm 增加,判断工资范围是否锁定 结束


            //拼接XML
            requestXml.append("<ZSP_DATE>" + strPfrq + "</ZSP_DATE>");

            //奖金金额
            String strJjje = Util.null2String(rs.getString("jjje"));
            log.info("奖金金额：" + strJjje);
            //拼接XML
            requestXml.append("<ZJE>" + strJjje + "</ZJE>" + "</item>");
        }
        requestXml.append("</T_9133>" +
                "</urn:ZHRI_075>" +
                "</soapenv:Body>" +
                "</soapenv:Envelope>");

        JSONObject jsonResult = toServices(requestXml.toString());
        log.info("最终返回值：" + jsonResult.toString());
        //返回的所有数据
        JSONArray jsonArray = jsonResult.getJSONArray("alldata");
        //根据顺序更新表
        rsSelect.executeQuery(strQyjlSql);
        //计数,SAP多返回一次,则下标从1开始
        int intCount = 1;
        while (rsSelect.next()) {
            //更新值
            String strUpdateVal = "1";
            //区经id
            String strId = Util.null2String(rsSelect.getString("id"));
            String strFlag = jsonArray.getJSONObject(intCount).getString("falg");
            //返回成功则更新值为0,否则为失败,1
            if ("S".equals(strFlag)) {
                strUpdateVal = "0";
            }
            String strUpdateSql = "update uf_qyjlpfhzb set tsjg =? where id=? ";
            log.info("更新sql:"+strUpdateSql+",id:"+strId+",结果:"+strUpdateVal);
            rsUpdate.executeUpdate(strUpdateSql, strUpdateVal, strId);
            intCount++;
        }

        return jsonResult.getString("point");
    }


    /**
     * 调用接口的方法
     *
     * @return
     */
    public JSONObject toServices(String requestXml) {

        BaseBean aa = new BaseBean();
        aa.writeLog("请求的requestXml：" + requestXml);
        //获取properties中接口地址值
        String strRealUrl = Util.null2String(aa.getPropValue("sapUrl", "sapZjk"));
        aa.writeLog("接口地址值：" + strRealUrl);
        //调用方法传入的参数
        String strEncoding = "UTF-8";
        String result = null;
        StringBuffer strTest = new StringBuffer();
        strTest.append("推送的所有明细表数据共有如下错误：（按错误个数排序）：");
        //区分是否全部是成功的
        String strFlag = "true";
        //sap返回的所有信息
        JSONArray jsonArray = new JSONArray();
        //方法返回
        JSONObject jsonReturn = new JSONObject();
        try {
            result = sendPost(strRealUrl, requestXml, strEncoding);

            //解析result
            //返回的xml
            log.info("返回的请求体：" + result);
            //获取返回结果
            JdeUtil jdeUtil = new JdeUtil();
            Document doc = null;
            try {
                doc = DocumentHelper.parseText(result.toString());
                //判断失败成功与否的字段
                Iterator<Element> its2 = doc.selectNodes("//TYPE").iterator();
                //错误信息
                Iterator<Element> its3 = doc.selectNodes("//MESSAGE").iterator();
                while (its2.hasNext()) {
                    //封存返回数据
                    JSONObject jsonObject = new JSONObject();
                    Element element = its2.next();
                    Element element3 = its3.next();
                    String Test = element3.getText();
                    String test = element.getText();
                    jsonObject.put("falg", test);
                    jsonObject.put("mess", Test);

                    if (test != null && test.equals("E")) {
                        log.info("返回的错误信息：" + Test);
                        strTest.append(Test + ";");
                        strFlag = "fail";
                    }
                    jsonArray.add(jsonObject);
                }
                //如果无失败返回
                if ("true".equals(true)) {
                    strTest = new StringBuffer("");
                }
                jsonReturn.put("alldata", jsonArray);
                jsonReturn.put("point", strTest);

            } catch (Exception e) {
                e.printStackTrace();
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonReturn;
    }


    public String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        log.info("请求地址=" + strUrl);
        log.info("请求xml=" + strRequestXml);

        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);

            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);

            //获取用户名
            String strUsername = Util.null2String(bb.getPropValue("sapUrl", "username"));
            //获取密码
            String strPassword = Util.null2String(bb.getPropValue("sapUrl", "password"));
            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                // log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }

        return strBody;
    }


}